package jp.sourceforge.akjrcp.util;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/*
 * this code from 
 * http://homepage2.nifty.com/igat/igapyon/diary/2002/ig021213.html
 */
public class MD5Util {

	public static String getMD5(File file,int size){
		 MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance("MD5");
			 DataInputStream in = new DataInputStream(new FileInputStream(file));
		        try {
		        	
		           for(int i=0;i<size;i++) {
		                byte b = in.readByte();
		              
		                md5.update(b);
		            }
		           
		        } catch (EOFException ignore) {
		        	
		        } catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		       
		        try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        
		        return toHexString(md5.digest());
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
       return null;
	}

    private static String toHexString(byte[] buf) {
        String s = "";
        for (int i = 0; i < buf.length; i++) {
            int n = buf[i] & 0xff;
            if (n < 16) {
                s += "0";
            } else {
                s += "";
            }
            s += Integer.toHexString(n).toUpperCase();
        }
        return s;
    }
}
